<template>
  <OneContextMenu :items="contextMenuItems" @click.right="getSelectedText">
    <div class="main-box" v-loading="loading" element-loading-svg-view-box="0, 0, 1024, 1024" :element-loading-svg="LoadingSvg">
        <MenuGroup :currentMessageId="currentMessageId" ref="menuGroupRef" @setUserBG="setUserBG" @isReadyUpdateFolderNum="isReadyUpdateFolderNum"  @onClick="onClick" v-if="isLoad" />
        <EmailContent  ref="emailContentRef" @getDetailFinished="getDetailFinished" @onClick="onClick" v-if="isLoad" />
        <!-- 写邮件、回复邮件 弹窗 -->
      <div v-show="isLoad">
        <WriteDialog ref="writeDialogRef" :currentMessageId="currentMessageId" />
        <!-- 移动邮件 -->
        <MoveEmail v-if="showMoveEmailDialog" @moveSuccess="moveSuccess" :messageId="messageId" @closeDialog="showMoveEmailDialog=false"  />
        <!-- 新建文件夹 -->
        <AddFolder ref="addFolderRef" />
        <!-- 翻译 -->
        <TranslateView ref="translateViewRef" />
        <el-tag style="position: absolute; bottom: 6px; right: 6px;">v{{ version }}</el-tag>
      </div>
    </div>
  </OneContextMenu>
</template>

<script lang="ts" setup>
import { ref, defineAsyncComponent, onMounted, onUnmounted, watch, computed, nextTick, onActivated } from 'vue';
import { storeToRefs } from 'pinia';
import { event } from '@tauri-apps/api';
import { LoadingSvg } from '/@/utils/loading';
import emailApi from '/@/api/email/index';
import { useEmail } from '/@/stores/email';
import pinia from '/@/stores/index';
import { ElMessage } from 'element-plus';
import commonApi from '/@/api/common';
import { Local } from '/@/utils/storage';
import { invoke } from '@tauri-apps/api/core';
import WriteDialog from './components/WriteDialog.vue';
// 事件相关
event.listen('emial_operate', (data: any) => onClick(data.payload.operate, data.payload.data));
event.listen('refreshFolder', () => queryAccontList(true));

defineOptions({ name: 'home' })

// 引入组件
const TranslateView = defineAsyncComponent(() => import('./components/translateView.vue'));
const MenuGroup = defineAsyncComponent(() => import('/@/components/folder/index.vue'));
const EmailContent = defineAsyncComponent(() => import('/@/components/EmailContent/index.vue'));
const MoveEmail = defineAsyncComponent(() => import('/@/views/home/components/moveEmail.vue'));
const AddFolder = defineAsyncComponent(() => import('/@/views/home/components/addFolder.vue'));
const OneContextMenu = defineAsyncComponent(() => import('/@/components/Common/OneContextMenu.vue'));

const showMoveEmailDialog = ref(false);
const isLoad = ref(false);
const originEmailId = ref();
const messageId = ref('');
const isReplyAll = ref(false);
const isForward = ref(false);
const addFolderRef = ref();
const appendContent = ref('');
const currentMessageId = ref<any>('');

const stores = useEmail(pinia);
const emailInitData = ref();
const emailContentRef = ref();
const version = ref('');
const translateViewRef = ref()


const { curAccount } = storeToRefs(stores);
const loading = ref(false);
const isGetDetailFinished = ref(false);
const isReadyToUpdateFolderNum = ref(false);
const menuGroupRef = ref();
const writeDialogRef = ref();
const selectedTextForReply = ref('');
// 选中的文本
const selectText = ref('')
const contextMenuItems = ref([{
    id: 'translate',
    label: '翻译',
    show: computed(() => !!selectText.value),
    action: (obj: any) => {
      const { event } = obj
      translateViewRef.value.translate({
          position: { left: event.clientX, top: event.clientY },
          data: selectText.value
      })
    }
  }, {
    id: 'reply_selected',
    label: '回复',
    show: computed(() => !!selectText.value),
    action: () => {
      onReplySelected({
          selectedText: selectText.value,
          emailData: {
            id: stores.currentId,
            messageId: currentMessageId.value
          }
      })
    }
  }
])

// 获取选中的内容
const getSelectedText = () => {
  const selection = window.getSelection();
  if (selection && selection.rangeCount > 0) {
    const selectedText = selection.toString();
    selectText.value = selectedText
  } else {
    selectText.value = ''
  }
}

// watch isReadyToUpdateFolderNum和isGetDetailFinished，连个都变成true时，刷新目录
watch([isReadyToUpdateFolderNum, isGetDetailFinished], () => {
  if (isReadyToUpdateFolderNum.value && isGetDetailFinished.value) {
    updateFolderNum();
    isReadyToUpdateFolderNum.value = false;
    isGetDetailFinished.value = false;
  }
})
const updateFolderNum = () => {
  // console.log('刷新目录')
  menuGroupRef.value.handlerRefresh();
};
onUnmounted(() => {
  stores.setEmailId('');
});

const isReadyUpdateFolderNum = (item:any) => {
  // console.log('准备刷新目录')
  isReadyToUpdateFolderNum.value = true;
  // console.log(item)
}

const setUserBG = (messageId:string, color:string) => {
  if (emailContentRef.value) {
    emailContentRef.value.setUserBG(messageId, color);
  }
}

const getDetailFinished = (messageId:any) => {
  // console.log("'获取邮件详情完毕'", messageId)
  currentMessageId.value = "";
  setTimeout(() => {
    currentMessageId.value =  messageId;
    isGetDetailFinished.value = true;
  }, 300);
}

const initFolder = async () => {
  const res = await commonApi.getUserInfo();
  if (res.code === 200) {
    Local.set('defaultFilePath', res.user.filePath || '');
  }
};

const getEmailList = async () => {
  try {
    const res = await emailApi.folder.getEmailList();
    return res.data; 
  } catch (error) {
    return [];
  }
};

const queryAccontList = async (refresh?: boolean) =>{
  if (!refresh) {
    if (stores.accountList.length) {
      isLoad.value = true;
      return;
    }
  }
  loading.value = true;
  const accountList = await getEmailList();
  let sum = 0;
  if(accountList.length) {
    accountList.forEach((item: any) => {
      item.unreadNum = item.folderList.reduce((sum: number, folder: any) => {
        return sum + folder.unreadNum;
      }, 0);
      sum = sum + item.unreadNum;
    });
    
    isLoad.value = true;
    stores.setAccountList(accountList);
    if (accountList.length) {
      // 刚登录时，初始化一下
      if (!curAccount.value) {
        stores.setAccount(accountList[0].account);
      }
      const account = accountList.find((f: { account: string; }) => f.account === curAccount.value);
      const folder = account.folderList[0];
      stores.setAccount(account.account);
      const folderName = folder.enName === 'inbox' ? 'INBOX' : folder.folderName;
      stores.setFolder(folderName);
    }
  }
  if (sum > 0) {
    invoke('update_tray_title', { title: sum.toString() });
  }
  loading.value = false;
};

const moveSuccess = () => {
  showMoveEmailDialog.value = false;
}

const clearForm = () => {
  appendContent.value = '';
  originEmailId.value = '';
  isReplyAll.value = false;
  isForward.value = false;
  messageId.value = '';
  emailInitData.value = null;
};

const onClick = (action: string, email: any) => {
  clearForm();
  // console.log(action);
  if (action === 'reply') {
    originEmailId.value = email.id;
    messageId.value = email.messageId;
    writeDialogRef.value.open('reply', email.id, email.messageId);
  } else if (action === 'replyAll') {
    isReplyAll.value = true;
    originEmailId.value = email.id;
    messageId.value = email.messageId;
    writeDialogRef.value.open('replyAll', email.id, email.messageId);
  } else if(action === 'forward') {
    isForward.value = true;
    originEmailId.value = email.id;
    messageId.value = email.messageId;
    writeDialogRef.value.open('forward', email.id, email.messageId);
  } else if (action === 'moveTo') {
    messageId.value = email.messageId;
    showMoveEmailDialog.value = true;
  } else if (action === 'addFolder') {
    addFolderRef.value.show(email);
  } else if (action === 'unRead') {
    handlerUnRead(email);
  } else if(action === 'writeEmail') {
    originEmailId.value = "";
    messageId.value = "";
    writeDialogRef.value.open('writeEmail');
  }
}

// 标记为未读
const handlerUnRead = async (email: any) => {
  const res = await emailApi.email.unread({
    account: curAccount.value,
    // folderName: curFolder.value,
    folderName: email.box,
    messageId: email.messageId
  });
  if (res.code === 200) {
    ElMessage({
      type: 'success',
      message: '操作成功',
    });
    // console.log(email)
    updateFolderNum();
    menuGroupRef.value.handlerToSwitchStatus('unRead', email.topMessageId)
    emailContentRef.value.handlerToSwitchStatus('unRead', email.id)
  }
};

const onReplySelected = (payload: any) => {
  console.log('onReplySelected payload:', payload);
  
  if (!payload) {
    console.error('payload is undefined');
    return;
  }
  
  const { selectedText, emailData } = payload;
  
  if (!emailData) {
    console.error('emailData is undefined');
    return;
  }
  
  if (!emailData.id || !emailData.messageId) {
    console.error('emailData missing required fields:', emailData);
    return;
  }
  
  selectedTextForReply.value = selectedText;
  
  // 使用现有的回复逻辑
  clearForm();
  originEmailId.value = emailData.id;
  messageId.value = emailData.messageId;
  writeDialogRef.value.open('reply', emailData.id, emailData.messageId, selectedText);
};

onMounted(async () => {
  // 查询账户列表
  await queryAccontList();
  // 设置目录
  initFolder();

	// 获取版本号并赋值给响应式变量
  try {
        console.log('开始获取版本号...');
        
        // 直接尝试调用 Tauri API，不依赖 window.__TAURI__ 检测
        try {
            const { getVersion } = await import('@tauri-apps/api/app');
            const appVersion = await getVersion();
            console.log('通过 import 成功获取应用版本:', appVersion);
            version.value = appVersion;
        } catch (tauriError) {
            console.log('Tauri API 调用失败:', tauriError);
            // 降级到手动设置
            version.value = '0.1.52';
            console.log('使用手动设置版本号:', version.value);
        }
    } catch (error) {
        console.error('获取版本号失败，详细错误:', error);
        // 最终降级方案
        version.value = '0.1.52';
        console.log('使用最终降级版本号:', version.value);
    }
});
onActivated(() => {
  const openWriteDialog = sessionStorage.getItem('openWriteDialog');
  if (openWriteDialog) {
    sessionStorage.removeItem('openWriteDialog');
    nextTick(() => {
      setTimeout(() => {
          onClick('writeEmail', {})
      }, 1000);
    })
  }
})
</script>
<style lang="scss" scoped>
.main-box {
  width: calc(100vw - 50px);
  height: 100vh;
  display: flex;
  position: relative;
}
</style>
